package com.ruoyi.loyj.service.impl;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.loyj.domain.DouyinClass;
import com.ruoyi.loyj.domain.DouyinPhoto;
import com.ruoyi.loyj.mapper.DouyinPhotoMapper;
import com.ruoyi.loyj.service.IDouyinClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.loyj.mapper.DouyinMapper;
import com.ruoyi.loyj.domain.Douyin;
import com.ruoyi.loyj.service.IDouyinService;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;
import static com.ruoyi.loyj.utils.spiderUtils.*;

/**
 * 抖音解析Service业务层处理
 *
 * @author loyj
 * @date 2021-09-10
 */
@Service
public class DouyinServiceImpl implements IDouyinService
{
    @Autowired
    private DouyinMapper douyinMapper;

    @Autowired
    private DouyinPhotoMapper douyinPhotoMapper;

    @Autowired
    private IDouyinClassService classService;
    /**
     * 查询抖音解析
     *
     * @param id 抖音解析主键
     * @return 抖音解析
     */
    @Override
    public Douyin selectDouyinById(String id)
    {
        return douyinMapper.selectDouyinById(id);
    }

    /**
     * 查询抖音解析列表
     *
     * @param douyin 抖音解析
     * @return 抖音解析
     */
    @Override
    public List<Douyin> selectDouyinList(Douyin douyin)
    {
        /*List<DouyinClass> douyinClasses = classService.selectDouyinClassList(null);
        List<String> douyinClassChildren = classService.getDouyinClassChildren(douyinClasses);
        System.out.println(douyinClassChildren);*/

        List<Douyin> douyins = douyinMapper.selectDouyinList(douyin);
        return douyins;
    }


    /**
     * 新增抖音解析
     *
     * @param douyin 抖音解析
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDouyin(Douyin douyin)
    {
        int i = 0;
        for (Douyin dy: getInfo(douyin.getShareUrl())) {
            dy.setShareUrl("https://v.douyin.com/" + regexMatch(douyin.getShareUrl(), "douyin.com/(.*?)/")+"/");
            dy.setId(IdUtils.fastSimpleUUID());
            dy.setClassId(douyin.getClassId());
            dy.setCreateBy(getUsername());
            dy.setCreateTime(DateUtils.getNowDate());
            // 该条抖音有照片，存储
            if(dy.getPhotos() != null && dy.getPhotos().size() > 0){
                List<DouyinPhoto> dyPhotos = new LinkedList<>();
                for (String photo : dy.getPhotos()) {
                    dyPhotos.add(new DouyinPhoto(IdUtils.fastUUID(), dy.getId(), photo));
                }
                douyinPhotoMapper.batchInsertDouyinPhoto(dyPhotos);
            }
            i = douyinMapper.insertDouyin(dy);
        }
        return i;
    }

    /**
     * 修改抖音解析
     *
     * @param douyin 抖音解析
     * @return 结果
     */
    @Override
    public int updateDouyin(Douyin douyin)
    {
        int i = 0;
        for (Douyin dy: getInfo(douyin.getShareUrl())) {
            dy.setShareUrl("https://v.douyin.com/" + regexMatch(douyin.getShareUrl(), "douyin.com/(.*?)/")+"/");
            dy.setId(douyin.getId());
            dy.setUpdateBy(getUsername());
            dy.setUpdateTime(DateUtils.getNowDate());
            i += douyinMapper.updateDouyin(dy);
        }
        return i;
    }

    /**
     * 批量删除抖音解析
     *
     * @param ids 需要删除的抖音解析主键
     * @return 结果
     */
    @Override
    public int deleteDouyinByIds(String[] ids)
    {
        return douyinMapper.deleteDouyinByIds(ids);
    }

    /**
     * 删除抖音解析信息
     *
     * @param id 抖音解析主键
     * @return 结果
     */
    @Override
    public int deleteDouyinById(String id)
    {
        return douyinMapper.deleteDouyinById(id);
    }

    /**
     * 获取信息
     *
     * @param shareStr 抖音分享的信息
     * @return 结果
     */
    public List<Douyin> getInfo(String shareStr){
        List<Douyin> list = new ArrayList<>();
        String url = "https://v.douyin.com/" + regexMatch(shareStr, "douyin.com/(.*?)/");
        String src = requireUrl(url).url().toString();
        // 提取URL中视频id
        String id  = regexMatch(src, "video/(.*?)/");
        if(id != null) {
            // 拼接并请求接口
            String jk = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids="+id;
            String json = requireUrl(jk).body();

            JSONObject jsonObject = JSON.parseObject(json);
            JSONArray item_list = jsonObject.getJSONArray("item_list");
            item_list.forEach(item -> {
                list.add(getAllDouyinInfo(JSON.parseObject(item.toString())));
            });
        }
        return list;
    }


    /**
     * 提取JSON中相关信息.
     *
     * @param json json
     * @return 结果
     */
    public Douyin getAllDouyinInfo(JSONObject json){
        Douyin douyin = new Douyin();
        douyin.setTitle(json.getString("desc"));
        douyin.setAuthor(json.getJSONObject("author").getString("nickname"));
        douyin.setCommentCount(json.getJSONObject("statistics").getLong("comment_count"));
        douyin.setDiggCount(json.getJSONObject("statistics").getLong("digg_count"));
        douyin.setShareCount(json.getJSONObject("statistics").getLong("share_count"));
        // 提取图片，如果有图片，则没有视频
        JSONArray images = json.getJSONArray("images");
        if(images != null && images.size() > 0){
            douyin.setPhotos(extractImagesFromJsonAarray(images, "url_list"));
        }else {
            String noWatermarkUrl = json.getJSONObject("video").getJSONObject("play_addr").getJSONArray("url_list").getString(0).replaceAll("playwm","play");
            if(!noWatermarkUrl.contains("obj")){
                douyin.setNoWatermarkUrl(noWatermarkUrl);
            }
        }


        JSONObject music = json.getJSONObject("music");
        if(music != null){
            douyin.setMusicTitle(music.getString("title"));
            douyin.setMusicUrl(music.getJSONObject("play_url").getString("uri"));
        }
        return douyin;
    }

    /**
     * 从JsonArray中提取url.
     * @param jsonArray the json array
     * @return the list
     */
    private List<String> extractImagesFromJsonAarray(JSONArray jsonArray, String targetStr){
        List<String> images = new LinkedList<>();
        for (Object o : jsonArray) {
            JSONObject imageObj = (JSONObject) o;
            images.add(imageObj.getJSONArray(targetStr).get(0).toString());
        }
        return images;
    }
}
